package net.yegong;

import static net.yegong.FileTypeCheck.FileType.BIN;
import static net.yegong.FileTypeCheck.FileType.IMG;
import static net.yegong.FileTypeCheck.FileType.UNKNOWN;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

import net.yegong.gdal.GdalInfo;

public class FileTypeCheck {

	public enum FileType {
		IMG, BIN, UNKNOWN
	}

	public static final String TITLE = "PCA-RS-FILE";

	public static void check(OutputStream os) throws IOException {
		ObjectOutputStream oos = new ObjectOutputStream(os);
		oos.writeObject(TITLE);
		oos.flush();
	}

	public static void check(InputStream is) throws IOException {
		Object obj;
		try {
			ObjectInputStream ois = new ObjectInputStream(is);
			obj = ois.readObject();
		}
		catch (Exception e) {
			throw new IOException("This file is not a pca-rs zip file");
		}
		if (obj != null && TITLE.equals(obj)) {
			return;
		}
		throw new IOException("This file is not a pca-rs zip file");
	}

	public static FileType detect(File file) throws IOException {
		try {
			GdalInfo info = new GdalInfo(file);
			if (info.isValid()) {
				return IMG;
			}
			try {
				InputStream is = null;
				try {
					is = new FileInputStream(file);
					check(new FileInputStream(file));
				}
				finally {
					if (null != is) {
						is.close();
					}
				}
				return BIN;
			}
			catch (IOException e) {
			}
		}
		catch (Exception e) {
			throw new IOException(String.format("Can't open the file [%s].", file.toString()));
		}
		return UNKNOWN;
	}
}
